import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

//扫描指定目录，并找到名称或者内容中包含指定字符的所有普通文件（不包含目录）
public class HomeWork3 {
    public static void main(String[] args) throws IOException {
        //1.输入信息
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入要查询的目录路径: ");//这里输入目录
        String srcPath = scanner.next();
        System.out.println("请输入查询的关键字: ");
        String searchWord = scanner.next();

        //2.判断路径
        File file = new File(srcPath);
        if(!file.isDirectory()){
            //因为输入的是目录
            System.out.println("输入的目录路径非法!");
            return;
        }
        searchFile(file,searchWord);
    }

    private static void searchFile(File file,String searchWord) throws IOException {
        File[] files = file.listFiles();
        if(files==null){
            //目录为空
            System.out.println("目录为空!");
            return;
        }
        for (File f:files){
            if (f.isFile()){
                matchWord(f,searchWord);
            } else if (f.isDirectory()) {
                searchFile(f,searchWord);
            }
        }
    }

    private static void matchWord(File f,String searchWord) throws IOException {
        try(Reader reader = new FileReader(f)) {
            StringBuilder stringBuilder = new StringBuilder();
            while (true){
                int c = reader.read();
                if(c==-1){
                    break;
                }
                stringBuilder.append(c);
            }
            if(stringBuilder.indexOf(searchWord)>=0){
                System.out.println("找到了 "+ f.getAbsolutePath());
            }
        }catch (IOException e){
            throw new IOException(e);
        }
    }
}
